//
//  HealthClockApp.swift
//  HealthClock
//
//  Created by 任建勇 on 2025/1/4.
//

import SwiftUI

@main
struct HealthClockApp: App {
    @NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
    
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
        .windowStyle(.hiddenTitleBar)
        .windowResizability(.contentSize)
        .defaultSize(width: 200, height: 220)
    }
}

class AppDelegate: NSObject, NSApplicationDelegate {
    func applicationDidFinishLaunching(_ notification: Notification) {
        // 使用 .regular 策略，保持在程序坞中显示
        NSApp.setActivationPolicy(.regular)
        
        // 延迟一小段时间后显示主窗口，确保窗口已经完全初始化
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
            if let window = NSApp.windows.first {
                window.makeKeyAndOrderFront(nil)
                NSApp.activate(ignoringOtherApps: true)
            }
        }
    }
    
    func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool {
        // 只有在用户点击Dock图标时才显示窗口，通知点击不会触发这个方法
        if let window = NSApp.windows.first {
            window.makeKeyAndOrderFront(nil)
            NSApp.activate(ignoringOtherApps: true)
        }
        return true
    }
    
    func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
        // 修改为 false，这样即使所有窗口都关闭，应用也不会退出
        return false
    }
}
